import requests
import json

def handler_factory(model: str, base_url: str = "http://localhost:5001"):
    """
    Replacement for DeepSeek API. This version calls a local Flask server
    with the same handler interface.
    """
    def handler(query: str):
        headers = {
            "Content-Type": "application/json"
        }
        data = {
            "user_id": "api_key",  # 用 api_key 作为 user_id，用于区分上下文
            "message": query,
            "model_name":model,
            "generation_config": {
                "min_length": 1,
                "max_length": 1024,
                "top_p": 0.9,
                "top_k": 50,
                "temperature": 1.0,
                "repetition_penalty": 1.0,
                "do_sample": False,
            }
        }

        response = requests.post(
            f"{base_url}/api/chat",
            headers=headers,
            json=data,
            stream=True
        )

        for line in response.iter_lines():
            if line and line.startswith(b"data: "):
                # print(line[len(b"data: "):].decode("utf-8"))
                yield json.dumps({"message":json.loads(line[len(b"data: "):].decode("utf-8"))})
    return handler
